﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

using System.IO;
using System.Diagnostics;

namespace LinqToFileSystem
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

            var dir = new DirectoryInfo(@"C:\Projects");

            // output a tree!
            string tree = dir.DescendantsAndSelf().Aggregate("",
                (bc, n) => bc + n.Ancestors().Aggregate("", (ac, m) => (m.ElementsAfterSelf().Any() ? "| " : "  ") + ac,
                ac => ac + (n.ElementsAfterSelf().Any() ? "+-" : "\\-")) + n.Name + "\n");

            Debug.WriteLine(tree);


            // find all directories that contain projects checked into SVN
            var dirs = dir.Descendants()
                          .Where(d => d.Elements().Any(i => i.Name == ".svn"))
                          .Where(d => !d.Ancestors().FirstOrDefault().Elements().Any(i => i.Name == ".svn"));

            foreach (var d in dirs)
            {
                Debug.WriteLine(d.FullName);
            }


            // find all directories that contain XML files, and output
            // the number of XML files they contain.            
            var dirsWithXML = 
                from d in dir.Descendants().Where(d => d.Name == "bin").Descendants()
                    let xmlCount = d.Files().Where(i => i.Extension == ".xml").Count()
                    where xmlCount > 0
                    select new{ Directory = d, XmlCount = xmlCount};
                

            foreach (var d in dirsWithXML)
            {
                Debug.WriteLine(d.Directory.FullName + " [" + d.XmlCount + "]");
            }

        }
    }
}
